package org.luxor.accesslog.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.luxor.accesslog.annotation.AccessLog;
import org.luxor.accesslog.entity.AccessLogEntity;
import org.luxor.accesslog.entity.AccessLogQuery;
import org.luxor.accesslog.service.IAccessLogService;
import org.luxor.commons.core.validator.ValidatorUtils;
import org.luxor.commons.core.validator.group.AddGroup;
import org.luxor.commons.core.web.RestStatus;
import org.luxor.commons.core.web.controller.BaseRestController;
import org.luxor.commons.core.web.data.R;
import org.luxor.commons.elasticsearch.metadata.EsPageQuery;
import org.luxor.commons.elasticsearch.metadata.EsPageResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * 访问审计日志模块
 *
 * @author Mr.yan @date 2020/3/15
 */
@RestController
@RequestMapping("/sys/access_log")
@Api(tags = "访问审计日志")
public class AccessLogController extends BaseRestController {

    private static final Logger logger = LoggerFactory.getLogger(AccessLogController.class);

    @Resource
    private IAccessLogService accessLogService;

    @PostMapping("/list")
    @ApiOperation("分页列表查询")
    @PreAuthorize("hasPermission(#request,'sys:accesslog:list')")
    public R<EsPageResult<AccessLogEntity>> list(@RequestBody EsPageQuery<AccessLogQuery> searchPage) {
        try {
            AccessLogQuery condition = searchPage.getSearch();
            // 校验参数合法性
            ValidatorUtils.validateEntity(condition, AddGroup.class);
        } catch (Throwable e) {
            return R.failed(RestStatus.PARAM_ILLEGAL_FIELDS);
        }
        try {
            EsPageResult<AccessLogEntity> pageContext = accessLogService.pageContent(searchPage);
            return R.ok(pageContext);
        } catch (Throwable e) {
            logger.error("分页查询访问日志失败.", e);
            return R.failed(e.getMessage());
        }
    }

    @GetMapping("/flush")
    @PreAuthorize("hasPermission(#request,'sys:accesslog:flush')")
    @ApiOperation("清除历史记录(默认保留15天)")
    @AccessLog(message = "清楚历史访问日志(只保留最近15天的记录)")
    public R flush() {
        try {
            accessLogService.flush();
            return R.ok();
        } catch (Throwable e) {
            logger.error("清除历史访问日志失败.", e);
            return R.failed(e.getMessage());
        }
    }

}
